<template>
  <a-form
      :model="ruleForm"
      ref="ruleForm"
      v-bind="layout"
      :rules="rules"
      @finish="handleFinish"
  >
    <a-form-item label="合金名称" name="alloy_name">
      <a-input v-model:value="ruleForm.alloy_name" />
    </a-form-item>
    <a-form-item has-feedback label="合金代码" name="alloy_code">
      <a-input v-model:value="ruleForm.alloy_code" />
    </a-form-item>
    <a-form-item label="合金相图" name="alloy_phase_diagram">
      <a-upload
        :fileList="ruleForm.alloy_phase_diagramFileList"
        :beforeUpload="beforealloy_phase_diagramUpload"
        :headers="headers"
        @change="handlealloy_phase_diagramChange"
      >
        <a-button> <upload-outlined /> 选择 </a-button>
      </a-upload>
    </a-form-item>
    <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
      <a-button type="primary" :loading="submitting" html-type="submit">
        {{ submitting ? '提交中' : '确定' }}
      </a-button>
    </a-form-item>
  </a-form>
</template>
<script>
import { message } from 'ant-design-vue'
import { UploadOutlined } from '@ant-design/icons-vue'

export default {
  name: 'AddOrEditAlloyPhaseDiagram',
  // url !== ''则为编辑操作，否则为添加
  props: ['url'],
  emits: ['operate-success', 'operate-failed'],
  components: {
    UploadOutlined,
  },
  data() {
    let isValidStr = (str) => {
      return str.indexOf(" ") === -1;
    };
    let validateAlloyName = async (rule, value) => {
      if (value === "") {
        return Promise.reject("请选择合金名称");
      }
    };
    let validateAlloycode = async (rule, value) => {
      if (value === "") {
        return Promise.reject("请输入合金代码");
      }else {
        if (!isValidStr(value)) {
          return Promise.reject("合金代码含有非法字符")
        }
        return Promise.resolve();
      }
    }
    return {
      submitting: false,
      ruleForm: {
        alloy_name: '',
        alloy_code: '',
        alloy_phase_diagramFileList: [],
      },
      rules: {
        alloy_name: [
          {
            validator: validateAlloyName,
            trigger: "change",
            required: true,
            whitespace: true,
          },
      ],
        alloy_code: [
          {
            validator: validateAlloycode,
            trigger: 'change',
            required: true,
            whitespace: true,
          },
        ],
      },
      layout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 14 },
      },
      headers: {
        authorization: 'authorization-text',
      },
    }
  },
  mounted() {
    this.fetch()
  },
  methods: {
    // 从后端获取数据
    fetch() {
      if (this.url !== '') {
        this.axios
          .get(this.url)
          .then((res) => {
            const data = res.data
            this.ruleForm.alloy_name = data.alloy_name
            this.ruleForm.alloy_code = data.alloy_code
            if (data.alloy_phase_diagram_filename !== '') {
              // console.log('not null')
              this.ruleForm.alloy_phase_diagramFileList.push({
                uid: '-1',
                name: data.alloy_phase_diagram_filename,
              })
            }
          })
          .catch((error) => {
            console.log('Error', error.message)
          })
      }
    },
    handleFinish(values) {
      this.submitting = true
      const {
        alloy_phase_diagramFileList,
      } = this.ruleForm
      const formData = new FormData()
      formData.append('alloy_name', values.alloy_name)
      formData.append('alloy_code', values.alloy_code)
      alloy_phase_diagramFileList.forEach((file) => {
        // console.log(file.originFileObj)
        if ('originFileObj' in file) {
          formData.append('alloy_phase_diagram', file.originFileObj)
        }
      })
      if (this.url !== '') {
        if (this.ruleForm.alloy_phase_diagramFileList.length === 0) {
          formData.append('alloy_phase_diagram_empty', true)
        }
        this.axios
          .put(this.url, formData)
          .then(() => {
            this.submitting = false
            message.success('修改成功！')
            this.$emit('operate-success')
          })
          .catch((error) => {
            this.submitting = false
            message.error('修改失败！')
            this.$emit('operate-failed')
            console.log('Error', error.message)
          })
      } else {
        this.axios
          .post('/attachment_management/alloy_phase_diagram/', formData)
          .then(() => {
            this.submitting = false
            message.success('添加成功！')
            this.$emit('operate-success')
          })
          .catch((error) => {
            this.submitting = false
            message.error('添加失败！')
            this.$emit('operate-failed')
            console.log('Error', error.message)
          })
      }
    },
    beforealloy_phase_diagramUpload(file) {
      this.ruleForm.alloy_phase_diagramFileList = [
        ...this.ruleForm.alloy_phase_diagramFileList,
        file,
      ]
      return false
    },
    handlealloy_phase_diagramChange(info) {
      let fileList = [...info.fileList]
      // 取最后选择的文件
      fileList = fileList.slice(-1)
      this.ruleForm.alloy_phase_diagramFileList = fileList
    },
  },
}
</script>
